package com.yhg.pridicates;

import jakarta.validation.constraints.NotEmpty;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.cloud.gateway.handler.predicate.GatewayPredicate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

/*
* 自定义路由断言工厂VipRoutePredicateFactory
* 继承AbstractRoutePredicateFactory
 */
@Component
public class VipRoutePredicateFactory extends AbstractRoutePredicateFactory<VipRoutePredicateFactory.Config> {

    public VipRoutePredicateFactory() {
        super(Config.class);
    }

    @Override
    public Predicate<ServerWebExchange> apply(Config config) {
        return new GatewayPredicate() {
            @Override
            public boolean test(ServerWebExchange serverWebExchange) {

                ServerHttpRequest request =  serverWebExchange.getRequest();
                String first = request.getQueryParams().getFirst(config.getParam());
                if (StringUtils.hasText(first) && first.matches(config.getRegexp())) {
                    return true;
                }
                return false;
            }

            @Override
            public Object getConfig() {
                return config;
            }

            @Override
            public String toString() {
                return String.format("Query: param=%s regexp=%s", config.getParam(), config.getRegexp());
            }
        };
    }
    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("param", "regexp");
    }

    /*
    可以配置的参数
    */

    @Validated
    public static class Config {
        @NotEmpty
        private String param;
        @NotEmpty
        private String regexp;

        public @NotEmpty  String getParam() {
            return param;
        }

        public void setParam(@NotEmpty  String param) {
            this.param = param;
        }

        public @NotEmpty String getRegexp() {
            return regexp;
        }

        public void setRegexp(@NotEmpty  String regexp) {
            this.regexp = regexp;
        }
    }
}
